import { deleteRole, fetchRoleList, createRole, updateRole, queryRoleAuth } from '@/services/ant-design-pro/system';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useIntl, useModel, useRequest } from '@umijs/max';
import { Button, Drawer, Form, Input, message, Popconfirm, Tree } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import type { API } from '@/services/role';
import ProductCategoryMenu from './components/Menu';
const RoleList: React.FC = () => {
  const { menu } = useModel('roleModel');
  const { refreshData } = useModel('roleModel');
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RoleItem | undefined>();
  const [isEditMode, setIsEditMode] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [key, setKey] = useState('1');
  const [messageApi, contextHolder] = message.useMessage();
  const [menuTreeData, setMenuTreeData] = useState<any[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);

  const { run: delRun, loading: deleteLoading } = useRequest(deleteRole, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reloadAndRest?.();
      messageApi.success('删除成功');
      refreshData()
    },
    onError: () => {
      messageApi.error('Delete failed, please try again');
    },
  });

  const { run: fetchMenus } = useRequest(queryRoleAuth, {
    manual: true,
    onSuccess: (data) => {
      // setMenuTreeData(data);
      setCheckedKeys(data);
    },
  });

  const handleCategorySelect = (key: string) => {
    setKey(key);
    actionRef.current?.reload();
  };

  const handleSave = useCallback(
    async (values: API.RoleItem) => {
      if (isEditMode) {
        await updateRole({id:currentRow.id,roleCode:currentRow.roleCode, ...values, list: checkedKeys });
        messageApi.success('更新成功');
      } else {
        await createRole({ ...values, deptCode: key, list: checkedKeys });
        messageApi.success('添加成功');
      }
      setDrawerVisible(false);
      refreshData()
      actionRef.current?.reload();
    },
    [isEditMode, actionRef, currentRow, key, checkedKeys],
  );

  const columns: ProColumns<API.RoleItem>[] = [
    { title: '角色名称', dataIndex: 'roleName' },
    { title: '角色编码', dataIndex: 'roleCode' },
    { title: '角色描述', dataIndex: 'roleDescription' ,search: false},
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRow(record);
            setIsEditMode(true);
            form.setFieldsValue(record);
            fetchMenus({roleCode:record.roleCode});
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除该角色吗？"
          onConfirm={() => handleRemove(record.id)}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleRemove = useCallback(
    async (roleCode: string) => {
      await delRun({ id: roleCode });
    },
    [delRun],
  );

  return (
    <PageContainer header={{title:''}}>
      {contextHolder}
      <ProTable<API.RoleItem, API.PageParams>
        headerTitle="角色列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
            labelWidth: 'auto',
          }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              setCurrentRow(undefined);
              setIsEditMode(false);
              form.resetFields();
              setCheckedKeys([]);
              setDrawerVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            {/* <ProductCategoryMenu selectedKey={key} onCategorySelect={handleCategorySelect} /> */}
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        request={(params) => fetchRoleList({ ...params, deptCode: key })}
        columns={columns}
      />
      <Drawer
        title={isEditMode ? '编辑角色' : '新建角色'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        closable={false}
      >
        <Form form={form} onFinish={handleSave} initialValues={{}}>
          <Form.Item name="roleName" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item name="roleDescription" label="角色描述">
            <Input placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item label="菜单权限">
            <Tree
            defaultExpandAll
              checkable
              treeData={menu}
              checkedKeys={checkedKeys}
              fieldNames={{
                key: 'menuCode',
                title: 'menuName',
                children:'treeList'
              }}
              onCheck={(checked) => setCheckedKeys(checked as string[])}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={() => setDrawerVisible(false)} style={{ marginLeft: 8 }}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default RoleList;